from flask import session
from flask_restful import Resource

from database import Database

class InsertOrder(Resource):

    def post(self):

        # TODO get books from book table where bookId == cart table.bookId
        # TODO check if the quantity of books in cart + quantity of books in profile <= limit
        # TODO set books status to unavailable
        # TODO create order entity, store orderid in a value
        # TODO create linebooks with the books and set order id for every line book
        # TODO return order details as json to the user

        db = Database()
        user_id = session.get("username")

        #TODO refactor all of it into functions, so it is easier to read
        #TODO convert books from the cart into linebooks

        #TODO function get cart books
        query = "select * from cart where userId=%s"
        items = db.execute_query(query, (user_id,))
        books = []

        #because books are unique and their quantity is always 1
        cartQuantity = len(items)

        #TODO function get borrowed qunatity
        query = "SELECT COUNT(*) FROM linebook WHERE userId = %s AND status = 'borrowed';"
        borrowedQuantity = db.execute_query(query, (user_id,))

        #TODO function get borrow limit
        query = "SELECT borrowLimit FROM useraccount WHERE userId = %s;"
        allQuantity = db.execute_query(query, (user_id,))


        if cartQuantity + borrowedQuantity[0][0] <= allQuantity[0][0]:

            #TODO function change book status
            for item in items:
                book_id = item[0]
                db.execute_query("UPDATE book SET status='Not Available' where bookId = %s", (book_id,))

            #what if there are no orders in the system yet?
            #what is this check for?
            orderIds = db.execute_query("SELECT * FROM orderids ")
            orderId = str(orderIds[0])



            if orderId:

                #TODO function create order
                query = """INSERT INTO order (orderId, userId, status, quantity, class) VALUES (%s, %s, %s, %s, %s)"""
                db.execute_query(query, (orderId, user_id, 'in process', cartQuantity, 'Borrow'))
                #what are orderIds table is for, if we can access all the orders in orders table?
                db.execute_query("UPDATE orderids SET OrderID = OrderID + 1")
                date = db.execute_query("SELECT dateCreated FROM `order` WHERE orderId = %s", (orderId,))  # Fix here
                for item in items:
                    book_id = item[0]
                    query = ("INSERT INTO linebook (orderId, userId, status, bookId, libraryAddress, borrowedTill) "
                             "VALUES (%s, %s, %s, %s, %s, %s)")
                    values = (orderId, user_id, 'borrowed', book_id, '', date)
                    db.execute_query(query, values)

            #fix what?
            #TODO function form order data
            query="select * from order where orderId=%s"
            order=db.execute_query(query,(orderId,))
            lineBooks = db.execute_query("SELECT * FROM linebook WHERE orderId = %s", (order[0],))
            listBooks_json = []
            if lineBooks:
                for linebook in lineBooks:
                    print(linebook[0])
                    book = db.execute_query("SELECT * FROM book WHERE bookId = %s", (linebook[3],))  # Fix here
                    book_data = {
                        "bookId": book[0],
                        "categoryId": book[1],
                        "imageUrl": book[2],
                        "stackId": book[3],
                        "ownerId": book[4],
                        "condition": book[5],
                        "fee": str(book[6]),
                        "price": str(book[7]),
                        "status": book[8],
                        "LineBookStatus": linebook[2],
                        "libraryAddress": linebook[4],
                        "borrowedTill": str(linebook[5]),
                        "returnAfter": str(linebook[6]),
                        "dayToken": str(linebook[7])
                    }
                    listBooks_json.append(book_data)
            order_data = {
                "orderId": order[0],
                "userId": order[1],
                "dateCreated": order[2].strftime("%Y-%m-%d %H:%M:%S"),
                "status": order[3],
                "quantity": order[4],
                "class": order[5],
                "listBooks": listBooks_json  # Changed to listBooks
            }
            return order_data
        else:
            return {"message": "fail"}, 400

